package com.iteye.weimingtom.cimmod;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PushServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger logger = LoggerFactory.getLogger(PushServlet.class);
    
    public PushServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/json; charset=UTF-8");	
		//logger.debug("=======>push");
    	Map<String, Object> input = new HashMap<String, Object>();
       	Map<String, Object> output = new HashMap<String, Object>();
        handleJsonResponse(input, request.getParameter("ctx"));
		processInput(input, output);
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		PrintWriter writer = response.getWriter();
    	String json = JSONObject.toJSONString(output);	
		writer.print(json);
		writer.flush();
	}
	
	@SuppressWarnings("unchecked")
	private void handleJsonResponse(Map<String, Object> input, String ctx) {
    	JSONParser jsonParser = new JSONParser();
    	Map<String, Object> temp = null;
		try {
			if (ctx != null) {
				temp = (Map<String, Object>) jsonParser.parse(ctx);
			}
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
    	if (temp != null && input != null) {
    		input.putAll(temp);
    	}
	}
	
	private void processInput(Map<String, Object> input, Map<String, Object> output) {
		String token = input.get("token") != null ? input.get("token").toString() : "";
		String act = input.get("act") != null ? input.get("act").toString() : "";
		if (act.equals("reconnect") || token.equals("") ||
			!TokenManager.getInstance().contains(token)) {
			token = createToken();
			output.put("token", token);
    	} else {
    		TokenManager.getInstance().refresh(token);
    		output.put("token", token);
    	}
		
		output.put("replyType", "");
		output.put("replyContent", "");
		String sendType = input.get("sendType") != null ? input.get("sendType").toString() : "";
		String sendContent = input.get("sendContent") != null ? input.get("sendContent").toString() : "";
		if (sendType.equals("login")) {
			if (TokenManager.getInstance().login(token, sendContent)) {
				output.put("replyType", "loginReply");
				output.put("replyContent", sendContent);
			}
		}

		output.put("totalToken", TokenManager.getInstance().getTotalToken());
		output.put("totalAliveToken", TokenManager.getInstance().getTotalAliveToken());	
	}
	
	private String createToken() {
		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
		TokenManager.getInstance().insert(uuid);
		return uuid;
	}
}
